package com.ideaction.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ideaction.entity.activity.ActivityModel;
import com.ideaction.entity.activity.MissionBean;
import com.ideaction.entity.activity.PlayerMissionData;
import com.ideaction.entity.player.Player;
import com.ideaction.game.xmldata.ISample;
import com.ideaction.game.xmldata.SampleContainer;
import com.ideaction.globalconst.Result;
import com.ideaction.globalconst.SysteamConst;
import com.ideaction.req.PlayerCommonReqBody;
import com.ideaction.utils.activity.ActivityLimitInterface;
import com.ideaction.xmldata.sample.Mission;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


@Slf4j
@Service
public class ActivityService {
    
    private Map<Integer, ActivityModel> activityMap = new ConcurrentHashMap<>();
    
    private Map<Integer, ActivityLimitInterface> a = new HashMap<>();
    
    @Autowired
    private SampleContainer<ISample> sampleContainer;
    
    public ActivityService() {
        //todo 清晰一些
        a.put(1, (x, y) -> true);//不管
        a.put(2, (x, y) -> y < x.getRewardCount());//总数在内就行
        a.put(3, (x, y) -> {
            long rewardTime = x.getRewardTime();
            long l = LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli();
            //求余 天数
            long l1 = l / SysteamConst.ODAY * SysteamConst.ODAY;
            return rewardTime == 0 || rewardTime < l1;
        });//每天一领
    }
    
    @Autowired
    private MongoTemplate playerMongoTemplate;
    
    @Autowired
    private PlayerServiceImp playerServiceImp;
    
    public String getActivityMessage(PlayerCommonReqBody playerCommonReqBody) {
        synchronized (ActivityService.class) {
            Date now = new Date();
            List<ActivityModel> list = new ArrayList<>();
            activityMap.forEach((x, y) -> {
                Date showTime = y.getShowTime();
                Date endShowTime = y.getEndShowTime();
                if (null != showTime && showTime.before(now)) {
                    if (null != endShowTime && endShowTime.after(now)) {
                        list.add(y);
                    }
                }
            });
            return JSON.toJSONString(list);
        }
    }
    
    public void updateActivityData() {
        synchronized (ActivityService.class) {
            log.info("===============更新活动开始=================");
            List<ActivityModel> activityModels = playerMongoTemplate.findAll(ActivityModel.class);
            if (null == activityModels || activityModels.isEmpty()) {
                log.info("===============没有活动数据！===========");
                return;
            }
            activityModels.forEach(x -> {
                activityMap.put(x.getSid(), x);
            });
        }
    }
    
    /**
     * 没有数据可能返回null
     *
     * @param userId
     * @param sid
     * @return
     */
    // todo 可以加一个null判定提示注解
    public MissionBean findMissionBean(String userId, Integer sid) {
        Query query = Query.query(Criteria.where("userId").is(userId));
        PlayerMissionData playerClientData = playerMongoTemplate.findOne(query, PlayerMissionData.class);
        if (null == playerClientData) {//这个对象没有
            //插入新对象
            playerClientData = new PlayerMissionData(userId);
            playerMongoTemplate.save(playerClientData);
        }
        Map<Integer, MissionBean> missionMap = playerClientData.getMissionMap();
        MissionBean missionBean = missionMap.get(sid);
        return missionBean;
    }
    
    
    public void addMissionCount(String userId, Integer sid, MissionBean missionBean) {
        Query query = Query.query(Criteria.where("userId").is(userId));
        Update update = new Update();
        update.set("missionMap." + sid, missionBean);
        playerMongoTemplate.updateFirst(query, update, PlayerMissionData.class);
    }
    
    
    public Result getActivityReward(PlayerCommonReqBody playerCommonReqBody) {
        Result build = Result.build();
        String sid = playerCommonReqBody.getParam("sid");
        String userId = playerCommonReqBody.getUserId();
        ActivityModel activityModel = activityMap.getOrDefault(Integer.parseInt(sid), new ActivityModel());//todo null处理
        Date beginTime = activityModel.getBeginTime();
        Date endTime = activityModel.getEndTime();
        //todo 判断时间区域 时间戳
        Date date = new Date();
        if (date.after(beginTime) && date.before(endTime)) {//时间范围内
            int sid1 = activityModel.getSid();
            MissionBean missionBean = findMissionBean(userId, sid1);
            if (null == missionBean) {
                missionBean = new MissionBean(sid1);
            }
            //todo 外面不要暴露这个map 不要改
            Mission mission = sampleContainer.getSample(Mission.class, sid1);
            ActivityLimitInterface activityLimitInterface = a.get(mission.getCountType());
            boolean limitResult = activityLimitInterface.getLimitResult(missionBean, mission.getCount());
            
            //看看是否允许 报错 暂时注释掉
            build.put("IsAble", limitResult);
            if (limitResult) {
                //                missionBean.addRewardCount();
                //                //todo 要改一下数据存在 resourcedata中
                //                Player one = playerServiceImp.findPlayer(userId);
                //                JSONObject playerClientData = one.getPlayerClientData();
                //                if (null == playerClientData) {
                //                    playerClientData = new JSONObject();
                //                    playerClientData.setUserID(userId);
                //                }
                //                int diamond = playerClientData.getDiamond();
                //                int diamond1 = mission.getDiamond();
                //                build.put("diamond", diamond + diamond1);
                //                playerServiceImp.addDiamond(userId, diamond1);
                //                addMissionCount(userId, sid1, missionBean);//todo 方法名改为save
            }
        } else {
            build.put("IsAble", false);
            build.put("TimeOut", true);//在时间之外
        }
        return build;
    }
}
